package com.hk.core.authentication.api.validatecode;

import lombok.Setter;
import org.springframework.cache.Cache;
import org.springframework.cache.concurrent.ConcurrentMapCache;

import java.util.Objects;

/**
 * @author kevin
 * @date 2018-07-27 14:09
 */
@Setter
public class SpringCacheValidateCodeStrategy<C extends ValidateCode> implements ValidateCodeStrategy<C> {

    private Cache cache = new ConcurrentMapCache("ValidateCodeStrategy");

    @Override
    public void save(C value) {
        cache.put(value.getId(), value);
    }

    @Override
    public C get(C validateCode, Class<C> clazz) {
        var valueWrapper = cache.get(validateCode.getId());
        return Objects.isNull(valueWrapper) ? null : clazz.cast(valueWrapper.get());
    }

    @Override
    public void remove(C validateCode) {
        cache.evict(validateCode.getId());
    }
}
